﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Caching;
using System.Xml;
using Channelvn.Cached.Common;
using System.Data;
using BAL;

namespace Rewrite
{
    public class _301Redirection
    {
        #region Config file object
        private List<RedirectRule> RedirectRules;
        public struct RedirectRule
        {
            public RedirectRule(string url, string parameters, string method)
            {
                this.Url = url;
                this.Parameters = parameters;
                this.Method = method;
            }
            public string Url, Parameters, Method;
        }

        public _301Redirection()
        {
            string cacheName = "Cache_OldUrlRedirectionRules";
            RedirectRules = HttpContext.Current.Cache[cacheName] as List<RedirectRule>;
            if (null == RedirectRules)
            {
                RedirectRules = new List<RedirectRule>();

                try
                {
                    string configFilePath = HttpContext.Current.Server.MapPath("/Config/OldRewriteRules.config");
                    XmlDocument xmlDoc = new XmlDocument();
                    xmlDoc.Load(configFilePath);

                    XmlNodeList nlstRules = xmlDoc.DocumentElement.SelectNodes("//rules/rule");

                    for (int i = 0; i < nlstRules.Count; i++)
                    {
                        RedirectRule rule = new RedirectRule();
                        rule.Url = nlstRules[i].SelectSingleNode("url").InnerText;
                        rule.Parameters = nlstRules[i].SelectSingleNode("params").InnerText;
                        rule.Method = nlstRules[i].SelectSingleNode("method").InnerText;

                        RedirectRules.Add(rule);
                    }

                    XmlNode nodeFileSettingCacheExpire = xmlDoc.DocumentElement.SelectSingleNode("//Configuration/RedirectRulesFile");
                    long fileSettingCacheExpire = Lib.Object2Long(nodeFileSettingCacheExpire.Attributes["cacheExpire"].Value);
                    if (fileSettingCacheExpire <= 0)
                    {
                        fileSettingCacheExpire = 3600;// default 1h
                    }

                    CacheDependency fileDependency = new CacheDependency(configFilePath);
                    HttpContext.Current.Cache.Insert(cacheName, RedirectRules, fileDependency, DateTime.Now.AddSeconds(fileSettingCacheExpire), TimeSpan.Zero, CacheItemPriority.Normal, null);
                }
                catch (Exception ex)
                {
                }
            }
        }

        public bool Redirect(string currentUrl)
        {
            bool mustRedirect = false;

            Regex rex;

            for (int i = 0; i < RedirectRules.Count; i++)
            {
                RedirectRule rule = RedirectRules[i];
                rex = new Regex(rule.Url, RegexOptions.IgnoreCase);
                Match match = rex.Match(currentUrl);

                if (match.Success)
                {
                    string parameters = rex.Replace(currentUrl, rule.Parameters);
                    mustRedirect = (bool)this.GetType().InvokeMember(rule.Method, System.Reflection.BindingFlags.InvokeMethod, null, this, new object[] { parameters.Split(',') });
                    break;
                }

            }

            return mustRedirect;
        }
        #endregion

        #region Redirect methods

        public static bool Redirect_List(string[] parameters)
        {
            string urlFormat = "/{0}/{1}.htm";
            string newUrl = "";

            #region Get new url

            try
            {
                string catDisplayURL = parameters[1];
                string catDisplayURLChild = parameters[3];
                newUrl = string.Format(urlFormat, catDisplayURL, catDisplayURLChild);
            }
            catch
            {
            }

            #endregion

            return RedirectTo(newUrl);
        }

        public static bool Redirect_ListIndex(string[] parameters)
        {
            string urlFormat = "/{0}/{1}/trang-{2}.htm";
            string newUrl = "";

            #region Get new url

            try
            {
                string catDisplayURL = parameters[1];
                string catDisplayURLChild = parameters[3];
                string pageIndex = parameters[4];

                newUrl = string.Format(urlFormat, catDisplayURL, catDisplayURLChild, pageIndex);
            }
            catch
            {
            }

            #endregion

            return RedirectTo(newUrl);
        }

        public static bool Redirect_ListDynamic(string[] parameters)
        {
            string urlFormat = string.Empty;
            string newUrl = "";

            #region Get new url

            try
            {
                //string parentid = parameters[0];
                //string cateid = parameters[1];

                //CategoryEntity ct = NewsPublishedController.Category(Convert.ToInt32(cateid));
                //if (ct.CatID == -1 || ct.CatParentID == -1) // nếu mục đã bị xóa chuyển sang trang suggest search
                //{
                //    RedirectTo("/404.aspx?KeySearch=" + ct.Cat_DisplayURL);
                //    return false;
                //}
                //else
                //{
                //    newUrl = ct.Href;
                //}
                
            }
            catch
            {
            }

            #endregion

            return RedirectTo(newUrl);
        }

        public static bool Redirect_ListDynamicIndex(string[] parameters)
        {
            string urlFormat = string.Empty;
            string newUrl = "";

            #region Get new url

            try
            {
                //string parentid = parameters[0];
                //string cateid = parameters[1];
                //string pageIndex = parameters[3];

                //CategoryEntity ct = NewsPublishedController.Category(Convert.ToInt32(cateid));
                //if (ct.CatID == -1 || ct.CatParentID == -1) // nếu mục đã bị xóa chuyển sang trang suggest search
                //{
                //    RedirectTo("/404.aspx?KeySearch=" + ct.Cat_DisplayURL);
                //    return false;
                //}
                //else
                //{
                //    newUrl = string.Format("{0}/trang-{1}.htm", ct.Href.Replace(".htm", ""), pageIndex);
                //}
               
            }
            catch
            {
            }

            #endregion

            return RedirectTo(newUrl);
        }

        public static bool Redirect_ListParent(string[] parameters)
        {
            string urlFormat = "/{0}.htm";
            string newUrl = "";

            #region Get new url

            try
            {
                string catDisplayURL = parameters[1];
                newUrl = string.Format(urlFormat, catDisplayURL);
            }
            catch
            {
            }

            #endregion

            return RedirectTo(newUrl);
        }

        public static bool Redirect_ListParentIndex(string[] parameters)
        {
            string urlFormat = "/{0}/trang-{1}.htm";
            string newUrl = "";

            #region Get new url

            try
            {
                string catDisplayURL = parameters[1];
                string pageIndex = parameters[2];
                newUrl = string.Format(urlFormat, catDisplayURL, pageIndex);
            }
            catch
            {
            }

            #endregion

            return RedirectTo(newUrl);
        }

        public static bool Redirect_NewsDetail(string[] parameters)
        {
            string urlFormat = "/{0}/{1}-{2}.htm";
            string newUrl = "";
            #region Get new url

            try
            {
                //string news_id = parameters[0];
                //string cat_id = parameters[1];
                //string news_title = parameters[3];


                //DataTable dt = NewsPublishedController.TinChiTiet(Convert.ToInt64(news_id));
                //if (dt != null && dt.Rows.Count > 0)
                //{
                //    DataRow dr = dt.Rows[0];
                //    newUrl = dr[Const.NewsContent.Url].ToString();
                //}

            }
            catch (Exception ex)
            {
            }

            #endregion

            return RedirectTo(newUrl);


        }

        #region Private methods
        public static bool RedirectTo(string url)
        {
            if (!string.IsNullOrEmpty(url))
            {
                string host = ConfigurationManager.AppSettings["Domain"];
                if (host.EndsWith("/")) host = host.Substring(0, host.Length - 1);

                HttpContext.Current.Response.Clear();
                HttpContext.Current.Response.Status = "301 Moved Permanently";
                HttpContext.Current.Response.AddHeader("Location", url.Contains("vnmoney.nld.com.vn") ? url : host + (url.StartsWith("/") ? "" : "/") + url);
                HttpContext.Current.Response.End();

                return true;
            }

            return false;
        }

        public static bool RedirectToMobile(string url)
        {
            if (!string.IsNullOrEmpty(url))
            {
                HttpContext.Current.Response.Clear();
                HttpContext.Current.Response.Status = "301 Moved Permanently";
                HttpContext.Current.Response.AddHeader("Location", url);
                HttpContext.Current.Response.End();


                return true;
            }

            return false;
        }
        #endregion
        #endregion
    }
}
